import secrets
from typing import List, Optional, Any
from pydantic_settings import BaseSettings
from pydantic import AnyHttpUrl, field_validator, PostgresDsn

class Settings(BaseSettings):
    API_V1_STR: str = "/api/v1"
    SECRET_KEY: str = secrets.token_urlsafe(32)
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7  # 7天

    # CORS配置
    BACKEND_CORS_ORIGINS: List[str] = [
        "http://127.0.0.1:5173",  # Your React frontend URL
        "http://localhost:3000",
        "http://localhost:8000",
    ]

    # 数据库配置
    POSTGRES_SERVER: str = "localhost"  # 默认值
    POSTGRES_USER: str = "postgres"  # 默认值
    POSTGRES_PASSWORD: str = "password"  # 默认值
    POSTGRES_DB: str = "university_ai_advisor"  # 默认值
    SQLALCHEMY_DATABASE_URI: str = "postgresql://postgres:postgresql@localhost:5432/university_ai_advisor"

    @field_validator("SQLALCHEMY_DATABASE_URI")
    @classmethod
    def assemble_db_connection(cls, v: Optional[str], info: Any) -> Any:
        if v:
            return v

        # 新版 Pydantic 使用不同的参数结构
        return str(PostgresDsn.build(
            scheme="postgresql",
            username=info.data.get("POSTGRES_USER"),
            password=info.data.get("POSTGRES_PASSWORD"),
            host=info.data.get("POSTGRES_SERVER"),
            path=f"/{info.data.get('POSTGRES_DB') or ''}",
        ))

    # # Redis配置
    # REDIS_HOST: str
    # REDIS_PORT: int
    # REDIS_DB: int
    # REDIS_PASSWORD: Optional[str] = None
    # USER_CACHE_EXPIRE_SECONDS: int = 60 * 60  # 1小时

    # 项目配置
    PROJECT_NAME: str = "University AI Advisor"

    class Config:
        case_sensitive = True
        env_file = ".env"

settings = Settings()